#include <setjmp.h>
#include "device.h"
#include "device_usart.h"
#include "modbus.h"
#include "stdio.h"
#include "gpio.h"
#include "speed_cnrt.h"
#include "usart.h"

jmp_buf main_loop_env;

void Main_Loop()
{
    LED_BLINK();
    Update_WatchDog();
    Update_IO();

    // 一帧消息接收完成
    if ((uart0_rx_pending && Uart0_FrameEnded()) || uart0_delay_process)
    {
        Delay_us(100); // 0.1ms
        USART_EN_OUT; 
        usart_interrupt_disable(USART0, USART_INT_RBNE);
        uart0_rx_pending = 0;
        REN0 = 0;
        Process_Request();
    }

    // 应答结束, 允许接收
    if (!REN0 && !uart0_tx_pending && !uart0_delay_process)
    {
        Delay_us(100); // 等待0.1ms, 确保EN
        USART_EN_IN; // 使能接收EN
        usart_interrupt_enable(USART0, USART_INT_RBNE);
        uart0_len = 0;
        uart0_rx_pending = 0;
        REN0 = 1;
    }

    if (srd_x.need_cleanup && srd_x.cleanup)
        srd_x.cleanup();
    if (srd_y.need_cleanup && srd_y.cleanup)
        srd_y.cleanup();
    if (srd_z.need_cleanup && srd_z.cleanup)
        srd_z.cleanup();
    if (srd_m.need_cleanup && srd_m.cleanup)
        srd_m.cleanup();
}

void Process_Main_Loop()
{
    Main_Loop();

    if (pending_action)
        longjmp(main_loop_env, 1);
}

int main()
{
    Device_Init();
    // 保存上下文, 以便从Process_Main_Loop中直接跳转到此
    setjmp(main_loop_env);

    while(1)
    {
        Main_Loop();
        // 处理动作
        if (pending_action)
        {
            pending_action = 0;
            Process_Action();
        }
    }
}



